package com.ficus.road.maintain.controller.smart;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ficus.road.maintain.converter.SmartHitConverter;
import com.ficus.road.maintain.core.exception.BadRequestException;
import com.ficus.road.maintain.core.model.*;
import com.ficus.road.maintain.core.model.smart.SmartHit;
import com.ficus.road.maintain.core.model.smartnew.*;
import com.ficus.road.maintain.core.model.test.HitImportExcelVO;
import com.ficus.road.maintain.core.model.test.RoadInfoImportExcelVO;
import com.ficus.road.maintain.core.model.test.RoadSectionImportExcelVO;
import com.ficus.road.maintain.dao.HitDao;
import com.ficus.road.maintain.dao.smartnew.*;
import com.ficus.road.maintain.dao.test.TestHitImportDao;
import com.ficus.road.maintain.dao.test.TestRoadInfoImportDao;
import com.ficus.road.maintain.dao.test.TestRoadSectionImportDao;
import com.ficus.road.maintain.dto.Checklist;
import com.ficus.road.maintain.dto.TestQueryDTO;
import com.ficus.road.maintain.handler.smartdecision.handlers.highway.SmartDecisionHandlerChainStarter;
import com.ficus.road.maintain.service.HitService;
import com.ficus.road.maintain.service.ZhonghaiClient;
import com.ficus.road.maintain.service.smartnew.primaryScreening.PrimaryRoadSectionService;
import com.ficus.road.maintain.util.FormatUtil;
import com.ficus.road.maintain.util.MyDateUtil;
import com.ficus.road.maintain.util.excel.ExcelUtil;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.gson.JsonObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.Min;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * @author xiawen yang
 * @date 2022/7/14 上午11:28
 */
@RestController
@RequiredArgsConstructor
@Slf4j
public class SmartV2Controller {
    private final SmartHighwayDao smartHighwayDao;
    private final SmartTableVerticalDao smartTableVerticalDao;
    private final SmartTableMergedDao smartTableMergedDao;
    private final HitService hitService;
    private final SmartDecisionResponseDao smartDecisionResponseDao;
    private final SmartValuationMergedDao smartValuationMergedDao;
    private final SmartValuationUnmergedDao smartValuationUnmergedDao;
    private final SmartDecisionHandlerChainStarter starter;
    private final PrimaryRoadSectionService primaryRoadSectionService;
    private final ZhonghaiClient zhonghaiClient;
    private final HitDao hitDao;
    private final TestHitImportDao testHitImportDao;
    private final TestRoadInfoImportDao testRoadInfoImportDao;
    private final TestRoadSectionImportDao testRoadSectionImportDao;

    /**
     * 智能巡查（公路）
     *
     * @param start
     * @param limit
     * @return
     */
    @RequestMapping(value = "/smartDiscovery/highway/inspection",
            produces = {"application/json"},
            method = RequestMethod.GET)
    @PreAuthorize("@rm.check('SMART')")
    public ResponseEntity<List<SmartHit>> listHighwayInspection(@Min(0) @Valid @RequestParam(defaultValue = "0") Integer start,
                                                                @Min(1) @Valid @RequestParam(defaultValue = "1000") Integer limit) {
//        Query query = new Query(Criteria.where("attrs.smart_roas_sec_type").is(RoadTypeEnum.HIGHWAY.toString()));
        Query query = new Query(Criteria.where("type").in(Lists.newArrayList("PIC_CRACK_RESULT_BROKEN_BOARD", "PIC_CRACK_RESULT_PIC_CRACK",
                "PIC_CRACK_RESULT_CAR_RUT", "PIC_POTHOLES_RESULT_SETTLEMENT", "PIC_CRACK_RESULT_CRACKED")));
        query.skip(start).limit(limit).with(new Sort(Sort.Direction.DESC, "first_hit_time"));
        List<Hit> hitList = hitService.findHitBySmart(query);
        List<SmartHit> smartHitList = hitList.stream().map(SmartHitConverter::convert).collect(Collectors.toList());
        return new ResponseEntity<>(smartHitList, HttpStatus.OK);
    }


    @RequestMapping(value = "/smartDiscovery/highway/inspectionOut",
            produces = {"application/json"},
            method = RequestMethod.GET)
    public ResponseEntity<List<Hit>> listHighwayInspectionOut(@RequestParam(defaultValue = "2024-01-01") String startTime, @RequestParam(defaultValue = "2024-02-01") String endTime) {
//        Query query = new Query(Criteria.where("attrs.smart_roas_sec_type").is(RoadTypeEnum.HIGHWAY.toString()));
//        Query query = new Query(Criteria.where("type").in(Lists.newArrayList("PIC_CRACK_RESULT_BROKEN_BOARD", "PIC_CRACK_RESULT_PIC_CRACK",
//                "PIC_CRACK_RESULT_CAR_RUT", "PIC_POTHOLES_RESULT_SETTLEMENT", "PIC_CRACK_RESULT_CRACKED")));
        Query query= new Query(Criteria.where("first_hit_time").gte(MyDateUtil.strParseDate(startTime, "yyyy-MM-dd").getTime() / 1000).lte(MyDateUtil.strParseDate(endTime, "yyyy-MM-dd").getTime() / 1000));
        query.addCriteria(Criteria
                .where("attrs.source").ne(SourceEnum.MOCK)
                .and("attrs.confirmation.status").is(Confirmation.ConfirmationStatus.CORRECT));
        List<Hit> hits = hitDao.findByQuery(query);
        return new ResponseEntity<>(hits, HttpStatus.OK);
    }


    /**
     * 项目初筛（公路）
     *
     * @return
     */
    @RequestMapping(value = "/smartDiscovery/highway/prescreening_bak",
            produces = {"application/json"},
            method = RequestMethod.GET)
    @PreAuthorize("@rm.check('SMART')")
    public ResponseEntity<List<SmartInitialScreening>> listHighwayInitialScreening() {
        return new ResponseEntity<>(new ArrayList<>(), HttpStatus.OK);
    }

    @RequestMapping(value = "/dataFlush/refreshGps",
            method = RequestMethod.GET)
    public ResponseEntity<String> refreshGps() {
        primaryRoadSectionService.createGpsRoadMap();
        return new ResponseEntity<>("success", HttpStatus.OK);
    }

    /**
     * 项目检测（公路）
     *
     * @return
     */
    @GetMapping("/smartDecision/highwayData/list")
    @PreAuthorize("@rm.check('SMART')")
    public ResponseEntity<List<SmartDecisionExcelVO>> highwayDataList() {
        List<SmartDecisionExcelVO> vo = smartHighwayDao.findAll();
        vo.sort(Comparator.comparing(SmartDecisionExcelVO::getRoadName)
                .thenComparing(SmartDecisionExcelVO::getStartStake)
                .thenComparing(SmartDecisionExcelVO::getDirection));
        return new ResponseEntity<>(vo, HttpStatus.OK);
    }

    /**
     * 日常养护（公路）, 智能发现
     *
     * @return
     */
    @RequestMapping(value = "/smartDiscovery/highway/maintenance",
            produces = {"application/json"},
            method = RequestMethod.GET)
    @PreAuthorize("@rm.check('SMART')")
    public ResponseEntity<List<SmartInitialScreening>> listHighwayMaintenanceInDiscovery() {
        return new ResponseEntity<>(new ArrayList<>(), HttpStatus.OK);
    }


    /**
     * 工程项目（公路）
     *
     * @return
     */
    @RequestMapping(value = "/smartInspect/highway/engineering",
            produces = {"application/json"},
            method = RequestMethod.GET)
    @PreAuthorize("@rm.check('SMART')")
    public ResponseEntity<List<SmartDecisionExcelVO>> listHighwayEngineering() {
        SmartDecisionResponse smartDecisionResponse = smartDecisionResponseDao.findAll().get(0);
        List<SmartDecisionExcelVO> res = smartHighwayDao.findByQuery(new Query(Criteria.where("_id").in(smartDecisionResponse.getSmartInspectionResponse().getProjectIds())));
        return new ResponseEntity<>(res, HttpStatus.OK);
    }

    /**
     * 日常养护（公路）, 智能检测
     *
     * @return
     */
    @RequestMapping(value = "/smartInspect/highway/maintenance",
            produces = {"application/json"},
            method = RequestMethod.GET)
    @PreAuthorize("@rm.check('SMART')")
    public ResponseEntity<List<SmartDecisionExcelVO>> listHighwayMaintenanceInInspection() {
        SmartDecisionResponse smartDecisionResponse = smartDecisionResponseDao.findAll().get(0);
        List<SmartDecisionExcelVO> res = smartHighwayDao.findByQuery(new Query(Criteria.where("_id").in(smartDecisionResponse.getSmartInspectionResponse().getMaintainIds())));
        return new ResponseEntity<>(res, HttpStatus.OK);
    }

    /**
     * 排分表（公路）
     *
     * @return
     */
    @GetMapping("/smartRank/highway/rankTable/road")
    @PreAuthorize("@rm.check('SMART')")
    public ResponseEntity<List<SmartTable>> smartTableRoadQuery() {
        List<SmartTable> all = smartTableMergedDao.findAll();
        all.sort(Comparator.comparing(SmartTable::getOrder).thenComparing(SmartTable::getTotalWeight, Comparator.reverseOrder()));
        return new ResponseEntity<>(all, HttpStatus.OK);
    }

    /**
     * 排分表（公路）, 按路段整合, 暂时没用了
     *
     * @return
     */
    @GetMapping("/smartRank/highway/rankTable/section")
    @PreAuthorize("@rm.check('SMART')")
    public ResponseEntity<List<SmartTable>> smartTableSectionQuery() {
        List<SmartTable> all = smartTableVerticalDao.findAll();
        all.sort(Comparator.comparing(SmartTable::getRoadName).thenComparing(SmartTable::getTotalWeight).reversed());
        return new ResponseEntity<>(all, HttpStatus.OK);
    }

    /**
     * 储备库（公路）
     *
     * @return
     */
    @RequestMapping(value = "/smartInspect/highway/warehouse",
            produces = {"application/json"},
            method = RequestMethod.GET)
    @PreAuthorize("@rm.check('SMART')")
    public ResponseEntity<List<SmartTable>> listHighwayWarehouse() {
        SmartDecisionResponse smartDecisionResponse = smartDecisionResponseDao.findAll().get(0);
        return new ResponseEntity<>(smartDecisionResponse.getSmartSortingResponse().getReservesBeforeMerged(), HttpStatus.OK);
    }

    /**
     * 合并的储备库（公路）
     *
     * @return
     */
    @RequestMapping(value = "/smartInspect/highway/mergedWarehouse",
            produces = {"application/json"},
            method = RequestMethod.GET)
    @PreAuthorize("@rm.check('SMART')")
    public ResponseEntity<List<SmartTable>> listHighwayMergedWarehouse() {
        SmartDecisionResponse smartDecisionResponse = smartDecisionResponseDao.findAll().get(0);
        List<SmartTable> reservesAfterMerged = smartDecisionResponse.getSmartSortingResponse().getReservesAfterMerged();
        //    reservesAfterMerged.sort(Comparator.comparing(SmartTable::getLastOverhaulYear, Comparator.reverseOrder()));
        return new ResponseEntity<>(reservesAfterMerged, HttpStatus.OK);
    }

    /**
     * 智能决策年度清单（公路）, 道路tab
     *
     * @return
     */
    @RequestMapping(value = "/smartDecision/highway/valuation1",
            produces = {"application/json"},
            method = RequestMethod.GET)
    @PreAuthorize("@rm.check('SMART')")
    public ResponseEntity<List<SmartValuation>> listHighwayValuation1() {
        List<SmartValuation> valuationList = smartValuationMergedDao.findAll();
        Map<String, List<SmartValuation>> collect = valuationList.stream().collect(Collectors.groupingBy(SmartDecisionExcelVO::getRoadName));
        List<SmartValuation> results = collect.values().stream().map(this::merge).sorted(Comparator.comparing(SmartTable::getOrder)
                .thenComparing(SmartTable::getWeight, Comparator.reverseOrder())).collect(Collectors.toList());
        results.forEach(item -> {
            if (item.getLength() != null) {
                item.setLength(FormatUtil.formatNumber(item.getLength()));
            }
        });
        return new ResponseEntity<>(results, HttpStatus.OK);
    }


    private SmartValuation merge(List<SmartValuation> list) {
        SmartValuation smartValuation = list.get(0);
        AtomicReference<Float> money = new AtomicReference<>((float) 0);
        AtomicReference<Float> pci = new AtomicReference<>((float) 0);
        AtomicReference<Float> pssi = new AtomicReference<>((float) 0);
        AtomicReference<Float> rdi = new AtomicReference<>((float) 0);
        AtomicReference<Float> rqi = new AtomicReference<>((float) 0);
        AtomicReference<Float> sri = new AtomicReference<>((float) 0);
        AtomicReference<Float> weight = new AtomicReference<>((float) 0);
        AtomicReference<Double> length = new AtomicReference<>((double) 0);
        list.forEach(i -> {
            money.updateAndGet(v -> (float) (v + i.getMoney()));
            if (i.getPCI() != null) {
                pci.updateAndGet(v -> (float) (v + i.getPCI()));
            }
            if (i.getPSSI() != null) {
                pssi.updateAndGet(v -> (float) (v + i.getPSSI()));
            }
            if (i.getRDI() != null) {
                rdi.updateAndGet(v -> (float) (v + i.getRDI()));
            }
            if (i.getRQI() != null) {
                rqi.updateAndGet(v -> (float) (v + i.getRQI()));
            }
            if (i.getSRI() != null) {
                sri.updateAndGet(v -> (float) (v + i.getSRI()));
            }
            if (i.getWeight() != null) {
                weight.updateAndGet(v -> (float) (v + i.getWeight()));
            }
            if (i.getWeight() != null) {
                length.updateAndGet(v -> v + i.getLength());
            }

        });
        int size = list.size();
        smartValuation.setMoney(money.get());
        smartValuation.setLength(length.get());
        smartValuation.setPCI((double) (pci.get() / size));
        smartValuation.setPSSI((double) (pssi.get() / size));
        smartValuation.setRDI((double) (rdi.get() / size));
        smartValuation.setRQI((double) (rqi.get() / size));
        smartValuation.setSRI((double) (sri.get() / size));
        smartValuation.setWeight((double) (weight.get() / size));
        return smartValuation;
    }

    /**
     * 智能决策年度清单（公路）, 路段tab
     *
     * @return
     */
    @RequestMapping(value = "/smartDecision/highway/valuation2",
            produces = {"application/json"},
            method = RequestMethod.GET)
    @PreAuthorize("@rm.check('SMART')")
    public ResponseEntity<List<SmartValuation>> listHighwayValuation2() {
        List<SmartValuation> valuationList = smartValuationUnmergedDao.findAll();
        Map<String, List<SmartValuation>> collect = valuationList.stream().collect(Collectors.groupingBy(t -> t.getRoadName() + t.getStartStake() + t.getEndStake()));
        List<SmartValuation> results = collect.values().stream().map(this::merge).sorted(Comparator.comparing(SmartTable::getOrder)
                .thenComparing(SmartTable::getWeight, Comparator.reverseOrder())).collect(Collectors.toList());
//        valuationList.sort(Comparator.comparing(SmartTable::getOrder).thenComparing(SmartTable::getWeight, Comparator.reverseOrder()));
        results.forEach(item -> {
            if (item.getLength() != null) {
                item.setLength(FormatUtil.formatNumber(item.getLength()));
            }
        });
        return new ResponseEntity<>(results, HttpStatus.OK);
    }

    /**
     * 智能决策年度清单（公路）, 合并路段tab
     *
     * @return
     */
    @RequestMapping(value = "/smartDecision/highway/valuation3",
            produces = {"application/json"},
            method = RequestMethod.GET)
    @PreAuthorize("@rm.check('SMART')")
    public ResponseEntity<List<SmartValuation>> listHighwayDecisionList() {
        List<SmartValuation> mergedValuations = smartValuationMergedDao.findAll();
        Map<String, List<SmartValuation>> collect = mergedValuations.stream().collect(Collectors.groupingBy(t -> t.getRoadName() + t.getGeneralDirection()));
        List<SmartValuation> results = collect.values().stream().map(this::merge).sorted(Comparator.comparing(SmartTable::getOrder)
                .thenComparing(SmartTable::getWeight, Comparator.reverseOrder())).collect(Collectors.toList());
        mergedValuations.forEach(item -> {
            if (item.getLength() != null) {
                item.setLength(FormatUtil.formatNumber(item.getLength()));
            }
        });
//        List<SmartValuation> unmergedValuations = smartValuationUnmergedDao.findAll();
//        mergedValuations.stream().filter(item -> item.getGroupId() != -1).forEach(merged -> {
//            double mergedMoney = unmergedValuations.stream().filter(unmerge ->
//                    Objects.equals(merged.getRoadName(), unmerge.getRoadName()) &&
//                            merged.getDirection().contains(unmerge.getGeneralDirection()) &&
//                            unmerge.getStartStake() >= merged.getStartStake() && unmerge.getEndStake() <= merged.getEndStake()
//            ).mapToDouble(SmartValuation::getMoney).sum();
//            merged.setMoney(mergedMoney);
//        });
//        mergedValuations.sort(Comparator.comparing(SmartTable::getOrder).thenComparing(SmartTable::getTotalWeight, Comparator.reverseOrder()));
        return new ResponseEntity<>(mergedValuations, HttpStatus.OK);
    }

    /**
     * 统计接口
     *
     * @return
     */
    @GetMapping("/smartDiscovery/total")
//    @PreAuthorize("@rm.check('SMART')")
    public ResponseEntity<List<SmartDecisionStatistic>> querySmartTotal() {
        SmartDecisionResponse smartDecisionResponse = new SmartDecisionResponse();
        SmartDecisionResponse smartDecisionResponse1 = smartDecisionResponseDao.findAll().get(0);
        if (smartDecisionResponse1 != null) {
            smartDecisionResponse = smartDecisionResponse1;
        }
        SmartDecisionStatistic smartDecisionStatistic = SmartDecisionResponse.convert2SmartDecisionStatistic1(smartDecisionResponse);
        smartDecisionStatistic.setScreening(primaryRoadSectionService.countAll());
        smartDecisionStatistic.setRoadType(RoadTypeEnum.HIGHWAY.toString());
        smartDecisionStatistic.setInspection(smartDecisionStatistic.getScreening() + smartDecisionStatistic.getEnd());
        return new ResponseEntity<>(Collections.singletonList(smartDecisionStatistic), HttpStatus.OK);
    }

    /**
     * 智能检测, 导入excel
     *
     * @param file
     * @return
     */
    @PostMapping("/smartDecision/import")
//    @PreAuthorize("@rm.check('SMART')")
    public ResponseEntity<String> importData(MultipartFile file) {
        try {
            log.info("filename:", file.getOriginalFilename());
            String fileName = file.getOriginalFilename();
            if (fileName == null) {
                throw new BadRequestException("fileName is null");
            }
            List<SmartDecisionExcelVO> res = ExcelUtil.excel2Collection(file.getInputStream(), SmartDecisionExcelVO.class, fileName);
//            log.info(res.toString());
            log.info("size:" + res.size());
            smartHighwayDao.deleteAll();
            res.parallelStream()
                    .map(SmartDecisionExcelVO::roadId)
                    .filter(Objects::nonNull)
                    .map(SmartDecisionExcelVO::completeAttr)
                    .forEach(item -> {
                        if (item.getArea() != null) {
                            item.setArea(FormatUtil.keepDecimalsOfK(item.getArea(), 2));
                        }
                        if (item.getLength() != null) {
                            item.setLength(FormatUtil.keepDecimalsOfK(item.getLength(), 2));
                        }
                        smartHighwayDao.saveOrUpdate(item);
                    });
            starter.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResponseEntity<>("success", HttpStatus.OK);
    }

    @GetMapping("/smartDecision/calculate")
    public ResponseEntity<String> calculate() {
        primaryRoadSectionService.calculate1();
        return new ResponseEntity<>("success", HttpStatus.OK);
    }

    @GetMapping("/smartDecision/calculate2")
    public ResponseEntity<Map<String, PrimaryRoadSectionDTO>> calculate(String roadDirection) {
        Map<String, PrimaryRoadSectionDTO> stringPrimaryRoadSectionDTOMap = primaryRoadSectionService.calculate2(roadDirection);
        return new ResponseEntity<>(stringPrimaryRoadSectionDTOMap, HttpStatus.OK);
    }


    @GetMapping("/smartDecision/hit/query")
    public ResponseEntity<String> modifyHit(@RequestParam(defaultValue = "2024-11-30") String startTime, @RequestParam(defaultValue = "2024-12-28") String endTime) {

        String roadDiseaseData = null;
        try {
            log.info("startTime" + startTime);
            log.info("endTime" + endTime);
            roadDiseaseData = zhonghaiClient.getRoadDiseaseData(startTime, endTime);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("获取中海数据失败:" + e.getMessage());
        }
        return new ResponseEntity<>(roadDiseaseData, HttpStatus.OK);
    }

    @GetMapping("/smartDecision/hit/query1")
    public ResponseEntity<List<Hit>> modifyHit1(@RequestParam(defaultValue = "2024-11-30") String startTime, @RequestParam(defaultValue = "2024-12-28") String endTime) {

        Query query = new Query(Criteria.where("type").in(Lists.newArrayList("PIC_CRACK_RESULT_BROKEN_BOARD", "PIC_CRACK_RESULT_PIC_CRACK",
                "PIC_CRACK_RESULT_CAR_RUT", "PIC_POTHOLES_RESULT_SETTLEMENT", "PIC_CRACK_RESULT_CRACKED")));
        query.skip(0).limit(1000).with(new Sort(Sort.Direction.DESC, "first_hit_time"));
        List<Hit> hitBySmart = hitService.findHitBySmart(query);
        return new ResponseEntity<>(hitBySmart, HttpStatus.OK);
    }

    //同步上下行信息
    @GetMapping("/smartDecision/hit/syncDirection")
    public ResponseEntity<List<Hit>> syncDirection(@RequestParam(defaultValue = "2024-11-01") String startTime, @RequestParam(defaultValue = "2024-11-30") String endTime) {
        Query query = new Query(Criteria.where("type").in(Lists.newArrayList("PIC_CRACK_RESULT_BROKEN_BOARD", "PIC_CRACK_RESULT_PIC_CRACK",
                "PIC_CRACK_RESULT_CAR_RUT", "PIC_POTHOLES_RESULT_SETTLEMENT", "PIC_CRACK_RESULT_CRACKED")));
        query.addCriteria(Criteria.where("first_hit_time").gte(MyDateUtil.strParseDate(startTime, "yyyy-MM-dd").getTime() / 1000).lte(MyDateUtil.strParseDate(endTime, "yyyy-MM-dd").getTime() / 1000));
        List<Hit> hitBySmart = hitDao.findByQuery(query);

        String roadDiseaseData = null;
        try {
            log.info("startTime" + startTime);
            log.info("endTime" + endTime);
            roadDiseaseData = zhonghaiClient.getRoadDiseaseData(startTime, endTime);
            int startIndex = roadDiseaseData.indexOf("<return>") + 8;
            int endIndex = roadDiseaseData.indexOf("</return>", startIndex);
            if (startIndex >= endIndex) {
                log.info("bad info");
            }
            String scoreDetail = roadDiseaseData.substring(startIndex, endIndex);
            String result = scoreDetail.replace("\\\"", "\"");


            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);  // 忽略未知字段
            try {
                List<RoadHitAttrs> roadDataList = objectMapper.readValue(result, objectMapper.getTypeFactory().constructCollectionType(List.class, RoadHitAttrs.class));

                for (int i = 0; i < hitBySmart.size(); i++) {
                    Hit hit = hitBySmart.get(i);
                    String roadDirection = "";
                    for (int j = 0; j < roadDataList.size(); j++) {
                        RoadHitAttrs roadHitAttrs = roadDataList.get(j);
                        if (roadHitAttrs.getSid().equals(hit.getId())) {
                            roadDirection = roadHitAttrs.getRoadDirction();
                        }
                    }
                    log.info("ID:" + hit.getId() + " roadDirection:" + roadDirection);
                    hit.getAttrs().setRoadDirection(roadDirection);
                    log.info("保存数据:" + hit.toString());
                    hitService.saveOrUpdate(hit);
                }
                // 输出解析后的数据
                for (RoadHitAttrs roadData : roadDataList) {
                    System.out.println("Road Direction: " + roadData.getRoadDirction());
                    System.out.println("Road Name: " + roadData.getRoadname());
                    // 添加其他需要的字段输出;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.info("获取中海数据失败:" + e.getMessage());
        }


        return new ResponseEntity<>(hitBySmart, HttpStatus.OK);


    }


    /**
     * 导入道路病害数据
     *
     * @param file
     * @return
     */
    @PostMapping("/hit/data/import")
//    @PreAuthorize("@rm.check('SMART')")
    public ResponseEntity<String> importHitData(MultipartFile file) {

        try {
            log.info("filename:", file.getOriginalFilename());
            String fileName = file.getOriginalFilename();
            if (fileName == null) {
                throw new BadRequestException("fileName is null");
            }
            List<HitExcelVO> res = ExcelUtil.excel2Collection(file.getInputStream(), HitExcelVO.class, fileName);
            log.info("size:" + res.size());
            hitDao.deleteAll();
            List<Hit> hitList = new ArrayList<>();
            for (int i = 0; i < res.size(); i++) {
                Hit hit = res.get(i).convertHit();
                if (hit != null) {
                    hitList.add(hit);
                }
                if (hitList.size() == 1000) {
                    hitDao.insert(hitList);
                    hitList.clear();
                }
            }
            if (hitList.size() != 0) {
                hitDao.insert(hitList);
                hitList.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResponseEntity<>("success", HttpStatus.OK);
    }

    @GetMapping("/hit/getOne")
//    @PreAuthorize("@rm.check('SMART')")
    public ResponseEntity<Hit> getOneHit() {
        Hit hit = hitDao.findOne(new Query());
        return new ResponseEntity<>(hit, HttpStatus.OK);
    }


    /**
     * 导入道路病害数据
     *
     * @param file
     * @return
     */
    @PostMapping("/hit/import")
//    @PreAuthorize("@rm.check('SMART')")
    public ResponseEntity<String> importHit(MultipartFile file) {
        try {
            FileUtil.writeFromStream(file.getInputStream(), "/home/yituadmin/road-maintain-new/uploads/hitInfo.xlsx");
            log.info("filename:", file.getOriginalFilename());
            String fileName = file.getOriginalFilename();
            if (fileName == null) {
                throw new BadRequestException("fileName is null");
            }
            List<HitImportExcelVO> res = ExcelUtil.excel2Collection(file.getInputStream(), HitImportExcelVO.class, fileName);
            log.info("size:" + res.size());
            testHitImportDao.deleteAll();
            List<HitImportExcelVO> hitList = new ArrayList<>();
            for (int i = 0; i < res.size(); i++) {
                hitList.add(res.get(i));
                if (hitList.size() == 1000) {
                    testHitImportDao.insert(hitList);
                    hitList.clear();
                }
            }
            if (hitList.size() != 0) {
                testHitImportDao.insert(hitList);
                hitList.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResponseEntity<>("success", HttpStatus.OK);
    }

    @PostMapping("/hit/data/query")
    public PageInfo<HitImportExcelVO> getHitQuery(@RequestBody TestQueryDTO queryDTO) {

        Query query = new Query();
        System.out.println(JSONObject.toJSONString(queryDTO));

        // 判断 hitId 是否为空，如果不为空则加入查询条件
        if (queryDTO.getHitId() != null && !queryDTO.getHitId().trim().isEmpty()) {
            query.addCriteria(Criteria.where("hitId").regex(queryDTO.getHitId(), "i"));  // "i"表示忽略大小写
        }

        // 判断 hitName 是否为空，如果不为空则加入查询条件
        if (queryDTO.getHitName() != null && !queryDTO.getHitName().trim().isEmpty()) {
            query.addCriteria(Criteria.where("hitName").regex(queryDTO.getHitName(), "i"));  // "i"表示忽略大小写
        }


        PageInfo<HitImportExcelVO> hitImportExcelVOPageInfo = testHitImportDao.queryPage(queryDTO.getPageNumber(), queryDTO.getPageSize(), query);

        return hitImportExcelVOPageInfo;
    }


    @GetMapping("/hit/data/export")
    public void exportHitData(HttpServletResponse response) throws IOException {
//        List<HitImportExcelVO> list = testHitImportDao.findAll();

        byte[] bytes = FileUtil.readBytes("/home/yituadmin/road-maintain-new/uploads/hitInfo.xlsx");

//        byte[] excelData = ExcelUtil.exportListToExcel(list);

        // 设置响应头
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=hitList.xlsx");

        // 将 Excel 数据写入响应输出流
        response.getOutputStream().write(bytes);
        response.getOutputStream().flush();
    }


    @PostMapping("/roadInfo/import")
//    @PreAuthorize("@rm.check('SMART')")
    public ResponseEntity<String> importRoadInfo(MultipartFile file) {
        try {
            log.info("filename:", file.getOriginalFilename());
            String fileName = file.getOriginalFilename();
            if (fileName == null) {
                throw new BadRequestException("fileName is null");
            }
            List<RoadInfoImportExcelVO> res = ExcelUtil.excel2Collection(file.getInputStream(), RoadInfoImportExcelVO.class, fileName);
            System.out.println(JSONObject.toJSONString(res));
            log.info("size:" + res.size());
            testRoadInfoImportDao.deleteAll();
            List<RoadInfoImportExcelVO> hitList = new ArrayList<>();
            for (int i = 0; i < res.size(); i++) {
                hitList.add(res.get(i));
                if (hitList.size() == 100) {
                    testRoadInfoImportDao.insert(hitList);
                    hitList.clear();
                }
            }
            if (hitList.size() != 0) {
                testRoadInfoImportDao.insert(hitList);
                hitList.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResponseEntity<>("success", HttpStatus.OK);
    }


    @PostMapping("/roadInfo/query")
    public PageInfo<RoadInfoImportExcelVO> get(@RequestBody TestQueryDTO queryDTO) {

        Query query = new Query();

        // 判断 hitId 是否为空，如果不为空则加入查询条件
        if (queryDTO.getRoadName() != null && !queryDTO.getRoadName().trim().isEmpty()) {
            query.addCriteria(Criteria.where("roadName").regex(queryDTO.getRoadName(), "i"));  // "i"表示忽略大小写

        }
        PageInfo<RoadInfoImportExcelVO> hitImportExcelVOPageInfo = testRoadInfoImportDao.queryPage(queryDTO.getPageNumber(), queryDTO.getPageSize(), query);

        return hitImportExcelVOPageInfo;
    }


    @GetMapping("/roadInfo/export")
    public void exportRoadInfo(HttpServletResponse response) throws IOException {
        List<RoadInfoImportExcelVO> list = testRoadInfoImportDao.findAll();

        byte[] excelData = ExcelUtil.exportListToExcel(list);

        // 设置响应头
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=roadInfoList.xlsx");

        // 将 Excel 数据写入响应输出流
        response.getOutputStream().write(excelData);
        response.getOutputStream().flush();
    }


    @PostMapping("/roadSection/import")
//    @PreAuthorize("@rm.check('SMART')")
    public ResponseEntity<String> importRoadSection(MultipartFile file) {
        try {
            log.info("filename:", file.getOriginalFilename());
            String fileName = file.getOriginalFilename();
            if (fileName == null) {
                throw new BadRequestException("fileName is null");
            }
            List<RoadSectionImportExcelVO> res = ExcelUtil.excel2Collection(file.getInputStream(), RoadSectionImportExcelVO.class, fileName);
            System.out.println(JSONObject.toJSONString(res));
            testRoadSectionImportDao.deleteAll();
            List<RoadSectionImportExcelVO> hitList = new ArrayList<>();
            for (int i = 0; i < res.size(); i++) {
                hitList.add(res.get(i));
                if (hitList.size() == 100) {
                    testRoadSectionImportDao.insert(hitList);
                    hitList.clear();
                }
            }
            if (hitList.size() != 0) {
                testRoadSectionImportDao.insert(hitList);
                hitList.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResponseEntity<>("success", HttpStatus.OK);
    }


    @PostMapping("/roadSection/query")
    public PageInfo<RoadSectionImportExcelVO> getRoadSection(@RequestBody TestQueryDTO queryDTO) {

        Query query = new Query();

        // 判断 hitId 是否为空，如果不为空则加入查询条件
        if (queryDTO.getRoadName() != null && !queryDTO.getRoadName().trim().isEmpty()) {
            query.addCriteria(Criteria.where("roadName").regex(queryDTO.getRoadName(), "i"));  // "i"表示忽略大小写

        }
        if (queryDTO.getSectionId() != null && !queryDTO.getSectionId().trim().isEmpty()) {
            query.addCriteria(Criteria.where("sectionId").regex(queryDTO.getSectionId(), "i"));  // "i"表示忽略大小写

        }
        PageInfo<RoadSectionImportExcelVO> hitImportExcelVOPageInfo = testRoadSectionImportDao.queryPage(queryDTO.getPageNumber(), queryDTO.getPageSize(), query);

        return hitImportExcelVOPageInfo;
    }


    @GetMapping("/roadSection/export")
    public void exportRoadSection(HttpServletResponse response) throws IOException {
        List<RoadSectionImportExcelVO> list = testRoadSectionImportDao.findAll();

        byte[] excelData = ExcelUtil.exportListToExcel(list);

        // 设置响应头
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=roadSectionList.xlsx");

        // 将 Excel 数据写入响应输出流
        response.getOutputStream().write(excelData);
        response.getOutputStream().flush();
    }



}
